package top200;

import java.util.ArrayList;
import java.util.List;

public class leetcode57插入区间 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        int group = intervals.length;
        List<int[]> result = new ArrayList<>();
        boolean ins = false;
        for (int i = 0; i < group; i++) {
            if (intervals[i][1] < newInterval[0]) {
                result.add(new int[]{intervals[i][0],intervals[i][1]});
            } else if (intervals[i][0] <= newInterval[1]) {
                newInterval[0] = Integer.min(intervals[i][0], newInterval[0]);
                newInterval[1] = Integer.max(newInterval[1], intervals[i][1]);
            } else {
                if (!ins) {
                    ins = true;
                    result.add(newInterval);
                }
                result.add(new int[]{intervals[i][0],intervals[i][1]});
            }
        }
        if (!ins) {
            result.add(newInterval);
        }
        int size = result.size();
        int[][] arr = new int[size][2];
        for (int i = 0; i < size; i++) {
            arr[i] = result.get(i);
        }
        return arr;
    }
}
